package org.kfive.nova.io;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * Created by admin on 2017-04-29.
 */
public class PipedInputStreamExample {
    class ReadThread implements Runnable{

        private PipedInputStream in;

        public ReadThread(PipedInputStream in){
            this.in = in;
        }

        @Override
        public void run() {
            byte [] buff = new byte[128];
            try {
                StringBuffer sb = new StringBuffer();
                while (this.in.read(buff)!=-1){
                    sb.append(buff);
                }
                System.out.println("read thread:"+sb.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    this.in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class WriteThread implements Runnable{

        private PipedOutputStream out;

        public WriteThread(PipedOutputStream out){
            this.out = out;
        }

        @Override
        public void run() {

            try {
                Thread.sleep(5000);
                this.out.write("Java 内用 Unicode 编码存储字符，字符流处理类负责将外部的其他编码的字符流和 java 内 Unicode 字符流之间的转换。而类 InputStreamReader 和 OutputStreamWriter 处理字符流和字节流的转换。字符流（一次可以处理一个缓冲区）一次操作比字节流（一次一个字节）效率高".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    this.out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        try {
            in.connect(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PipedInputStreamExample example = new PipedInputStreamExample();
        ReadThread read =  example.new ReadThread(in);
        WriteThread write =  example.new WriteThread(out);
        new Thread(read).start();
        new Thread(write).start();
    }
}
